<?php
// +---------------------------------------------------------------------------+
// | This file is part of the KnowledgebasePublisher package                   |
// | KnowledgebasePublisher - web based knowledgebase publisher tool           |
// |                                                                           |
// | Author:  Evgeny Leontev <eleontev@gmail.com>                              |
// | Copyright (c) 2005 Evgeny Leontev                                         |
// |                                                                           |
// | For the full copyright and license information, please view the LICENSE   |
// | file that was distributed with this source code.                          |
// +---------------------------------------------------------------------------+

class KBClientSearchGenerator
{
	
	var $values = array();
	var $period = 'all';
	var $order;
	
	
	function KBClientSearchGenerator(&$values) {
		$this->values = &$values;
		if(!empty($values['period'])) { $this->period = $values['period']; }
		if(empty($values['in'])) { $this->values['in'] = 'article'; }
	}
	
	
	/*
	[search_period_range]
	all				= All time
	last_10_day		= Last 10 days
	last_30_day		= Last 30 days
	last_90_day		= Last 90 days
	last_1_year		= Last year
	custom			= Custom period
	*/
	function getDateParams() {
		
		if($this->period == 'all') { return '1'; }
				
		// added or updated
		@$field = ($this->values['pv'] == 'u') ? 'e.date_updated' : 'e.date_posted';
				
		switch ($this->period) {
		case 'custom': // ------------------------------
			
			$sql = 1;
			@$min = $this->values['from']['year'] . $this->values['from']['month'] . $this->values['from']['day'];
			@$max = $this->values['to']['year']  . $this->values['to']['month']  . $this->values['to']['day'];
			
			// we have date active
			if(!empty($this->values['is_from']) && !empty($this->values['is_to'])) {
				$sql = "$field BETWEEN '{$min}' AND '{$max}'";
			
			} elseif(!empty($this->values['is_from'])) {
				$sql = "$field >= '{$min}'";
			
			} elseif(!empty($this->values['is_to'])) {
				$sql = "$field <= '{$max}'";
			}
			
			break;
		
		default:
			
			//last_10_day...
			preg_match("/_(\d+)_(\w+)/", $this->period, $match);
			$sql = sprintf("%s + INTERVAL %s %s >= CURDATE()", $field, $match[1], strtoupper($match[2]));
			break;	
		}
		
		return $sql;
	}
	
	
	function getOrderSql() {
	
		$val = 'ORDER BY e.date_updated';
		if(!empty($this->values['q'])) {
			if($this->values['in'] != 'filename' && 
			   $this->values['in'] != 'article_id' &&
			   $this->values['in'] != 'article_keyword') {
				
				$val = 'ORDER BY score DESC';
			}
		}
		
		return $val; 
	}	
	
	
	function getFullSearchSql($view, $tables = array()) {
		
		$sql = array();
		$sql['select'] = '1';
		$sql['where'] = 1;
		$sql['from'] = '';
		
		// keywords
		if(!empty($this->values['q'])) {
			
			$str = mysql_escape_string(stripslashes($this->values['q']));
			
			// FILES
			if($view == 'files') {
				
		 		if($this->values['in'] == 'filename') {	
					
					$str = addslashes($str);
					$str = str_replace('*', '%', $str);
					$sql['where'] = "e.filename LIKE '$str'";
				
				//if($this->values['in'] == 'fileall') {
				} else {
					$sql['select'] = "MATCH (e.title, e.description, e.filetext) AGAINST ('$str') AS score";
                    if(SettingModel::getQuick(100, 'enable_fulltext')) {
                        $sql['where'] = "MATCH (e.title, e.description, e.filetext) AGAINST ('$str' IN BOOLEAN MODE)";
                    } else {
                        $sql['where'] = "(e.title LIKE '%$str%' OR e.description LIKE '%$str%' OR e.filetext LIKE '%$str%') ";
                    }
				}
			
			// ARTICLES
			} else {
			
				//attachments
				if($this->values['in'] == 'attachment') {
					
					$sql['select'] = "MATCH (f.title, f.description, f.filetext) AGAINST ('$str') AS score";
					if(SettingModel::getQuick(100, 'enable_fulltext')) {
                        $w[] = "MATCH (f.title, f.description, f.filetext) AGAINST ('$str' IN BOOLEAN MODE)";
                    } else {
                        $w[] = "(f.title LIKE '%$str%' OR f.description LIKE '%$str%' OR f.filetext LIKE '%$str%') ";
                    }
					$w[] = "AND e.id = a.entry_id";
					$w[] = "AND f.id = a.attachment_id";
					$w[] = "AND f.active = 1";
					
					$sql['where'] = implode("\n", $w);
					$sql['from'] = ',' . $tables[0] . ' f, ' . $tables[1] . ' a';			
				
				//title only
				} elseif ($this->values['in'] == 'article_title') {
					$sql['select'] = "MATCH (e.title) AGAINST ('$str') AS score";
                    if(SettingModel::getQuick(100, 'enable_fulltext')) {
                        $sql['where']  = "MATCH (e.title) AGAINST ('$str' IN BOOLEAN MODE)";
                    } else {
                        $sql['where']  = "e.title LIKE '%$str%'";
                    }
				//keywords
				} elseif ($this->values['in'] == 'article_keyword') {
					$str = addslashes($str);
					$sql['where'] = "e.meta_keywords LIKE '%$str%'";
				
				//article id
				} elseif ($this->values['in'] == 'article_id') {
					$search = array('#[\.,:;]#', '[ +]');
					$replace = array(',', '');
					$str = preg_replace($search, $replace, $str);
					
					foreach(explode(',', $str) as $v) { $ids[] = (int)$v; }
					$sql['where']  = sprintf("e.id IN (%s)", implode(',', $ids));	
					
				//title and body +
				} else {
					$sql['select'] = "MATCH (e.title, e.body, e.meta_keywords, e.meta_description) AGAINST ('$str') AS score";
					if(SettingModel::getQuick(100, 'enable_fulltext')) {
                        $sql['where']  = "MATCH (e.title, e.body, e.meta_keywords, e.meta_description) AGAINST ('$str' IN BOOLEAN MODE)";
                    } else {
                        $sql['where']  = "(e.title LIKE '%$str%' OR e.body LIKE '%$str%' OR e.meta_keywords LIKE '%$str%' OR e.meta_description  LIKE '%$str%') ";
                    }
                }
			}
		}
		
		//echo "<pre>"; print_r($sql); echo "</pre>";
		return $sql;
	}
	
	
	function getCategorySql($categories) {
		
		$sql = 1;
		
		// categories	
		if(!empty($this->values['c'])) {
			$c = implode(',', $this->values['c']);
			
			// all child
			if(!empty($this->values['cp'])) {
				
				$tree = &new TreeHelper();
				foreach($categories as $k => $row) {
					$tree->setTreeItem($row['id'], $row['parent_id']);
				}
				
				$child = array();
				foreach($this->values['c'] as $k => $v) {
					$_child = $tree->getChildsById($v);
					
					foreach($_child as $id) {
						if(!$id) { continue; }
						$child[] = $id;
					}
				}
				
				//echo "<pre>"; print_r($child); echo "</pre>";
				//echo "<pre>"; print_r($this->values['c']); echo "</pre>";
				//echo "<pre>"; print_r(array_unique(array_merge($child,$this->values['c']))); echo "</pre>";
				
				$c = implode(',', array_unique(array_merge($child, $this->values['c'])));
			}
			
			$sql = "e_to_cat.category_id IN($c)";
		}		
	
		return $sql;
	}
}
?>